<template>
    <div class="content">
        <el-dialog :visible.sync="addImportData.dialogLotImport"
        title="批量导入教师" size="tiny" :before-close="handleClose"
         class="up-file-dialog">
          <el-form ref="lotImports" :model="lotImports" :rules="rules" label-width="130px" @submit.native.prevent>
            <el-form-item label="选择学校" prop="schoolName">
                <el-row :gutter="20" type="flex" justify="space-between">
                    <el-col :span="20">
                        <school v-model="lotImports.schoolName" style="width:100%" @change='schoolChange'></school>
                    </el-col>
                </el-row>
            </el-form-item>
            <el-form-item label="请选择导入的教师">
              <el-row :gutter="20" type="flex" justify="space-between">
                <el-col :span="20">
                  <span class="urlText" v-cloak>
                    <el-row type="flex" class="row-bg" justify="space-between">
                      <el-col :span="6">
                        <el-button type="text" class="text">{{form.text}}</el-button>
                      </el-col>
                      <span>
                          <el-button v-if="delStart" @click="delFileUrl" type="text">
                          删除<i class="el-icon-close el-icon--right"></i>
                        </el-button>
                      </span>
                    </el-row>
                    <i v-if="expand" :style="`width:${progress}%`" class="expand"></i>
                  </span>
                </el-col>
                <span>
                  <template v-if="disabled">
                    <file-upload ref="upload" @onSuccess="successFn" :isAuto="true" @getFileName="getFileName"  @onProgress="progressFn" :up-file-type="fileOptions.upFileType">
                        <el-button  type="text" class="btn-success font-style-color" slot="trigger" size="small">选择文件</el-button>
                    </file-upload>
                  </template>
                  <template v-else>
                       <el-button type="text" class="btn-success font-style-color" @click="upTrigger"  size="small">选择文件</el-button>
                  </template>
                </span>
              </el-row>
              <div class="el-upload-text font-style-color">只能上传xlsx/xls文件,学校必填 <br>建议每次导入的教师数量不超过100人</div>
            </el-form-item>
            <div v-if="percentage == 100">
              <div v-if="delStart">
                <el-form-item label="校验结果：">
                  <p>数据无误，可上传！</p>
                </el-form-item>
              </div>
            </div>
            <div v-else>
              <div v-if="delStart">
                <el-form-item label="校验结果：">
                  <span class="title">数据校验中</span>
                    <el-row :gutter="20">
                      <el-col :span="20">
                        <el-progress :percentage="percentage"></el-progress>
                      </el-col>
                    </el-row>
                    <el-row :gutter="20">
                      <el-col :span="20">
                        <p>{{errorIng}}</p>
                      </el-col>
                    </el-row>
              </el-form-item>
              </div>
            </div>
            <div v-if="upError">
                <el-form-item label="错误信息：">
                    <el-row :gutter="20">
                      <el-col :span="20">
                        <p>{{errorIng}}</p>
                      </el-col>
                    </el-row>
                </el-form-item>
            </div>
            <el-form-item >
                <el-row :gutter="20" type="flex" justify="space-between">
                    <el-col :span="20">
                        <span class="font-style-color">
                            <a href="http://testdoc-1254059237.cossh.myqcloud.com/%E6%89%B9%E9%87%8F%E5%AF%BC%E5%85%A5%E6%95%99%E5%B8%88%E6%A8%A1%E6%9D%BF%20.xlsx">文件样式参考范本下载</a>
                        </span>
                    </el-col>
                </el-row>
            </el-form-item>
            <el-row :gutter="20" type="flex" class="row-bg" justify="center">
              <el-col :span="4">
                <el-button @click="close('lotImports')">关闭</el-button>
              </el-col>
              <el-col :span="4" >
                <el-button type="primary" :disabled="percentage !== 100" :loading="loading" @click="btnUp('lotImports')">上传</el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-dialog>
    </div>
</template>
<script>
import fileUpload from 'components/Upload/fileUpload';
import { verifyTeacherForImport, batchImportForTeacher } from 'api/teacherManage';
import school from 'components/SchoolClasss/school';
export default {
    components: {school, fileUpload},
    props: {
        addImportData: {
            default() {
                return {
                    dialogLotImport: false // 默认不显示
                }
            },
            required: true
        }
    },
    data() {
        var validatehave=(rule, value, callback) => {
            if (this.formInline.schoolId === '') {
                callback(new Error('该学校不存在'));
            } else {
                callback();
            }
        };
        return {
            fileObj: {},
            schoolImportLoading: false,
            formInline: {
                schoolId: '',
                chooseSchoolList: []// 模糊查找学校列表
            },
            lotImports: {
                file: '',
                schoolName: '',
                fileTitle: ''
            },
            rules: {
                file: [{ required: true, message: '请选择文件', trigger: 'blur' }],
                schoolName: [
                    { required: true, message: '请选择学校', trigger: 'blur' },
                    { validator: validatehave, trigger: 'blur,change' }
                ]
            },
      // 设置上传类型
            fileOptions: {
                upFileType: 'excel'
            },

      // 初始加载进度
            progress: 0,

      // 展示上传文件名称
            form: {
                text: ''
            },

      // 判断是否选择文件
            delStart: false,

      // 是否进度条滚动
            expand: false,

      // 上传loading
            loading: false,
            disabled: false,
            percentage: 0,
            timout: null,
            errorIng: '',
            upError: false
        };
    },
    watch: {
        'formInline.schoolId': {
            handler(val, oldVal) {
                // console.log('val', val, 'oldVal', oldVal)
                if (val) {
                    this.disabled = true;
                }
            },
            deep: true
        }
    },
    methods: {
        upTrigger() {
            this.$refs.lotImports.validateField('schoolName');
        },
 // 获取学校id
        schoolChange(val) {
            this.formInline.schoolId = val
        },
        progressFn(p) {
            this.progress = p.percent;
            this.expand = true;
        },
        successFn(obj) {
      // 判断是否拿到回调值
            this.upError = false;
            this.fileObj=obj;
            // 触发上传事件
            if (!this.fileObj.fileName) {
                this.$message({
                    message: '请先上传文件',
                    type: 'warning'
                });
            } else {
                // this.loading = true;
                let schoolId = this.formInline.schoolId;
                if (schoolId) {// 如果有该学校
                    verifyTeacherForImport(this.fileObj.imgUrl, this.fileObj.fileName, schoolId).then(res => {
                        this.percentage = 100;
                        this.progressIng(false);
                                // this.loading = false;
                        // this.delUrl();// 还原数据
                        // this.$emit('search-list');// 更新列表
                        // this.$message({
                        //     message: '恭喜你，上传成功！',
                        //     type: 'success'
                        // });
                    }).catch(res => {
                        this.errorIng = res;
                        this.progressIng(false)
                                // this.loading = false;
                    });
                } else {
                    this.$refs.lotImports.validateField('schoolName');
                }
            }
        },
        getFileName(obj) {
            this.form.text = obj.name;
            this.delStart = true;
        },
        handleClose() {
            this.$refs.lotImports.resetFields();
            // this.delUrl();
            if (this.loading) {
                this.$message('正在上传中......,请稍后刷新页面');
            }
            this.disabled = false;
            this.lotImports.schoolName = '';// 清空学校
            this.form.text = '';
            this.delStart = false;
            this.expand = false;
            this.loading = false;
            this.percentage = 0;
            this.addImportData.dialogLotImport = false;
            this.upError = false;
        },
        close(dataForm) {
            this.$refs[dataForm].resetFields();
            // this.delUrl();
            if (this.loading) {
                this.$message('正在上传中......,请稍后刷新页面');
            }
            this.disabled = false;
            this.lotImports.schoolName = '';// 清空学校
            this.form.text = '';
            this.delStart = false;
            this.expand = false;
            this.loading = false;
            this.percentage = 0;
            this.addImportData.dialogLotImport = false;
            this.upError = false;
        },
        delFileUrl() {
            // this.lotImports.schoolName = '';// 清空学校
            this.form.text = '';
            this.delStart = false;
            this.expand = false;
            this.loading = false;
            // this.disabled = false;
            clearInterval(this.timout);
            this.percentage = 0;
            this.upError = false;
        },
        delUrl() {
            this.addImportData.dialogLotImport = false;
            this.delFileUrl()
        },
        btnUp(val) {
            this.$refs[val].validate((valid) => {
                if (valid) {
                    this.loading = true;
                    this.delStart = false;
                    this.upError = false;
                    batchImportForTeacher(this.formInline.schoolId).then(res => {
                        this.loading = false;
                        this.delUrl();// 还原数据
                        this.lotImports.schoolName = '';// 清空学校
                        this.addImportData.dialogLotImport = false;
                        let newObj = {};
                        for (let x in res.data.content) {
                            newObj[x] = res.data.content[x];
                        }
                        this.$emit('importProgress', newObj);// 更新列表
                        // if (this.addImportData.provinceId) {
                        //    this.$emit('importProgress', newObj);// 更新列表
                        // }
                        // this.$message({
                        //     message: '上传成功，请稍后刷新页面！',
                        //     type: 'success'
                        // });
                    }).catch(Error => {
                        this.loading = false;
                        this.upError = true;
                        this.errorIng = Error;
                    })
                }
            });
        },
        progressIng(boolean) {
            if (boolean) {
                this.timout = setInterval(() => {
                    if (this.percentage <= (85 + Math.round(Math.random()*10))) {
                        this.percentage += Math.round(Math.random()*6)
                    } else {
                        clearInterval(this.timout);
                    }
                }, 500)
            } else {
                clearInterval(this.timout)
            }
        }
    }
};
</script>

<style lang="scss" scoped>
code {
  padding: 0;
  margin-bottom: 0;
  margin-top: 10px;
  background: transparent;
  text-align: center;
  a{
      color:#37a1fb;
  }
}

.urlText {
  position: relative;
  height: 36px;
  width: 100%;
  display: block;
  border: 1px solid rgb(217, 200, 191);
  padding: 0 10px;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  .text {
    width: 155px;
    display: inline-block;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .expand {
    position: absolute;
    width: 100%;
    height: 1px;
    margin: 2px 0;
    background: #37a1fb;
    bottom: -3px;
    left: 0;
    transition: all 5s;
  }
}
.del {
  padding-left: 5px;
  font-style: normal;
  cursor: pointer;
  color: rgb(32, 160, 255);
  i {
    padding-left: 5px;
    font-size: 12px;
  }
}
</style>
